/**
 * Copyright &copy; 2012-2015 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.zouqone.smc.modules.sys.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.zouqone.smc.common.persistence.Page;
import com.zouqone.smc.common.service.CrudService;
import com.zouqone.smc.common.utils.CacheUtils;
import com.zouqone.smc.modules.sys.entity.Menu;
import com.zouqone.smc.modules.sys.dao.MenuDao;
import com.zouqone.smc.modules.sys.utils.DictUtils;
import com.zouqone.smc.modules.sys.utils.LogUtils;
import com.zouqone.smc.modules.sys.utils.MenuUtils;
import com.zouqone.smc.modules.sys.utils.UserUtils;

/**
 * 菜单管理Service
 * @author zouqh
 * @version 2015-09-08
 */
@Service
@Transactional(readOnly = true)
public class MenuService extends CrudService<MenuDao, Menu> {
	@Autowired
	private MenuDao menuDao;
	
	public Menu get(String id) {
		Menu menu = super.get(id);
		   if(menu.getParent() != null && StringUtils.isEmpty(menu.getParent().getId())){
				Menu parent = MenuUtils.getMenu(menu.getParent().getId());
				menu.setParent(parent);
			}
	
		return menu;
	}
	
	public List<Menu> findList(Menu menu) {
		return setReferEntity(super.findList(menu));
	}
	
	public Page<Menu> findPage(Page<Menu> page, Menu menu) {
		Page<Menu> pages = super.findPage(page, menu);
		setReferEntity(pages.getList());
		return pages;
	}
	
	public List<Menu> setReferEntity(List<Menu> list){
		if(list!=null && list.size()>0){
			for (Menu e : list) {
									
			}
		}
		return list;
	}
	
	@Transactional(readOnly = false)
	public void save(Menu menu) {
		super.save(menu);
	}
	
	@Transactional(readOnly = false)
	public Integer save(List<Menu> menuList) {
		int count = 0;
		for (Menu menu : menuList) {
			save(menu);
			count++;
		}
		return count;
	}
	
	@Transactional(readOnly = false)
	public void delete(Menu menu) {
		menuDao.delete(menu);
		// 清除用户菜单缓存
		UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
		// 清除日志相关缓存
		CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
		//super.delete(menu);
	}
	
	@Transactional(readOnly = false)
	public Integer delete(List<Menu> menuList) {
		int count = 0;
		for (Menu menu : menuList) {
			delete(menu);
			count++;
		}
		return count;
	}
	
	@Transactional(readOnly = false)
	public void delete(String ids) {
		if(!StringUtils.isEmpty(ids)){
			String [] idArray = ids.split(",");
			for (String id : idArray) {
				Menu menu = super.get(id);
				delete(menu);
			}
		}
	} 
	
}